package com.github.lh.support;

import lombok.AllArgsConstructor;
import lombok.Builder;
import org.apache.commons.collections.iterators.ArrayIterator;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto: 393803588@qq.com">刘涵(Hanl)</a>
 * By 2017/12/3
 */
@Builder
@AllArgsConstructor
public class TableScanner {

    private String url = "jdbc:mysql://192.168.3.134:3306/test?charset=utf-8";
    private String user = "liuhan";
    private String pass = "liuhan";


    private Iterable<Table> iterator(ResultSet rs) throws SQLException {
        Map<String, Table> tableMap = new HashMap<>();
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            // get support
            Table table = tableMap.getOrDefault(tableName, new Table(tableName));
            // add column
            Column column =Column.builder()
                    .columnName(rs.getString("COLUMN_NAME"))
                    .dataType(TypeMapping.getType(rs.getString("DATA_TYPE")))
                    .columnDefault(rs.getObject("COLUMN_DEFAULT"))
                    .desc(rs.getString("COLUMN_COMMENT"))
                    .ordinal(rs.getInt("ORDINAL_POSITION"))
                    .isNullable("YES".equalsIgnoreCase(rs.getString("IS_NULLABLE")))
                    .isPrimary("PRI".equalsIgnoreCase(rs.getString("COLUMN_KEY")))
                    .isUnique("UNI".equalsIgnoreCase(rs.getString("COLUMN_KEY")))
                    .build();
            if (column.isPrimary()) {
                table.setPrimary(column);
            }

            table.getColumns().add(column);
            tableMap.putIfAbsent(tableName, table);
        }
        return tableMap.values();
    }

    public Iterable<Table> getTables() {

        try (Connection conn = DriverManager.getConnection(url, user, pass)) {
            String schema = conn.getCatalog();
            try (PreparedStatement ps = conn.prepareStatement("SELECT * from information_schema.COLUMNS WHERE TABLE_SCHEMA = ?")) {
                ps.setString(1, schema);
                try (ResultSet rs = ps.executeQuery()) {
                    return iterator(rs);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ArrayIterator::new;
    }


    public static void main(String[] args) throws SQLException {
        TableScanner ts = TableScanner.builder()
                .url("jdbc:mysql://192.168.3.134:3306/test?charset=utf-8")
                .user("liuhan")
                .pass("liuhan")
                .build();

        ts.getTables().forEach(System.out::println);
    }
}
